package com.dongman.config;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 跨域处理
 */
@WebFilter(filterName = "cross", urlPatterns = "/*")
public class CrossFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤器开始执行了");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String requestURI = request.getRequestURI();
        //tomcat里面的这家伙会导致两边请求
        if (requestURI.contains("favicon.ico")) {
            return;
        }
        //跨域请求时设置，网关也可以解决跨域问题
        HttpServletResponse httpResponse=(HttpServletResponse) servletResponse;
        httpResponse.addHeader("Access-Control-Allow-Origin", "*");
        httpResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        httpResponse.addHeader("Access-Control-Allow-Headers", "Content-Type");
        //30 min
        httpResponse.addHeader("Access-Control-Max-Age", "1800");
        httpResponse.setCharacterEncoding("UTF-8");
        filterChain.doFilter(request, servletResponse);
        System.out.println("过滤器执行之后");
    }

    @Override
    public void init(FilterConfig filterConfig) {
        System.out.println("init....");
    }

    @Override
    public void destroy() {
        System.out.println("destroye....");
    }
}
